import { adminRoute, businessManagementRoute } from '@/router/routes'
// import { wujieRouteDict } from '@/router/wujie'
import { useMessage } from '@fl/hooks/web/use-message'
import { useUserStoreWithOut } from '@fl/store/modules/user'
import { cloneDeep, intersection, uniqBy } from 'lodash-es'

export const businessTypeEnum = {
    1: {
        label: '联合运营平台',
        path: '/joint',
        remark: '联合运营',
    },
    2: {
        label: '武汉新房',
        path: '/new-house',
        remark: '新房业务',
    },
    3: {
        label: '武汉好房',
        path: '/good-house',
        remark: '好房业务',
    },
} as const

export function compositeMenuByEnterpriseType() {
    const businessTypeList = calcBusinessTypeList()
    const menuList = [] as any[]
    businessTypeList.forEach((businessType) => {
        if (businessTypeEnum[businessType])
            menuList.push(businessTypeEnum[businessType])
    })

    // 首次进入重定向
    window.sessionStorage.setItem('FIRST_REDIRECT', menuList[0]?.path || '/login')

    const uniqueMenuList = uniqBy(menuList, 'label')

    return uniqueMenuList
}

function calcBusinessTypeList() {
    // const userStore = useUserStoreWithOut()
    // const businessTypeStr = userStore.getOrgInfo?.catTypeId ?? ''
    const businessTypeStr = '1,2'
    // filter(item => item) 是排除空字符串
    const businessTypeList = businessTypeStr.replace(/，/g, ',').split(',').filter(item => item).sort()
    return businessTypeList
}

// 计算第一个有效路径, 根路由会跳转, 否则直接登出
export function calcFirstValidPath() {
    const { createMessage } = useMessage()

    const businessTypeList = calcBusinessTypeList()
    if (businessTypeList.length) {
        const redirectPath = businessTypeEnum[businessTypeList[0]].path
        console.log('businessTypeList2', businessTypeList, redirectPath)
        return redirectPath
    }
    else {
        createMessage.error('无法匹配子应用路径, 正在登出')
        const userStore = useUserStoreWithOut()
        userStore.logout()
    }
}

export function generateRoutesByEnterpriseType(): AppRouteRecordRaw[] {
    const bussinessTypeList = calcBusinessTypeList()
    const routes = [] as AppRouteRecordRaw[]

    bussinessTypeList.forEach((bussinessType) => {
        if (wujieRouteDict[bussinessType])
            routes.push(...wujieRouteDict[bussinessType])
    })

    const result = cloneDeep(routes)

    console.log(result, 'result')

    return result
}

// const modules = {
//     ...import.meta.glob('../../pages/**/*.{vue,tsx}'),
//     ...import.meta.glob('../../../../../packages/**/*.{vue,tsx}'),
// }
const Layout = () => import('@/layout/layout.vue')
const parentView = () => import('@/layout/components/ParentView/index.vue')
const modules = import.meta.glob('../../pages/**/*.{vue,tsx}')

export function generateRoutesByServer(asyncRouterMap) {
    const accessedRouters = asyncRouterMap.filter((route) => {
        route = toRaw(route)
        if (route.component) {
            // 转换组件
            if (route.component === 'Layout') {
                route.component = Layout
            }
            else if (route.component === 'parentView' || route.type === 1) {
                route.component = parentView
            }
            else if (route?.component?.includes('/fl/')) {
                const temp = route.component.slice(4) // 去掉/fl
                route.component = modules[`../../${temp}.vue`]
            }
            else {
                route.component = modules[`../../pages${route.component}.vue`]
            }
            // route.meta.hidden = route.hidden
            route.meta.noTagsView = route.hidden
            route.meta.activeMenu = route.activeMenu
        }

        if (route.children?.length) {
            route.children = generateRoutesByServer(route.children)
        }

        // 过滤掉只有目录没有子级的菜单
        if (route.type === 1 && (!route.children || route.children.length === 0)) {
            return false
        }

        return true
    })
    return accessedRouters
}

function renderName(str) {
    let name = ''
    if (str) {
        if (str.startsWith('/')) {
            // 如果字符串以斜杠开头，去掉第一个斜杠
            str = str.slice(1)
        }
        name = str.charAt(0).toUpperCase() + str.slice(1)
    }
    return name
}

function formatRouterItem(obj) {
    return {
        // ...obj,
        id: obj?.id || '',
        parentId: obj?.parentId || 0,
        name: renderName(obj?.name) + obj?.id,
        path: obj?.path && obj?.path?.startsWith('/') ? obj?.path?.slice(1) : obj?.path || '/',
        hidden: !obj.visible,
        sort: obj?.sort || 0,
        redirect: obj?.redirect || '',
        component: obj?.component || '',
        alwaysShow: obj?.alwaysShow || true,
        type: obj?.type || '',
        meta: {
            title: obj?.name,
            icon: obj?.icon,
            noCache: false,
            link: null,
            hidden: !obj.visible,
        },
        children: [], // 确保每个节点都有children属性
    }
}

type TreeNode = {
    id: string | number
    parentId: string | number
    path?: string
    component?: string
    sort?: number
    children?: TreeNode[]
    hidden?: boolean
    alwaysShow?: boolean
    redirect?: string
}

export function listToTree(list: any[], pid = 0, level = 1) {
    const nodeMap = new Map<string | number, TreeNode>()
    const result: TreeNode[] = []

    // 初始化所有节点并存入映射
    list.forEach((item) => {
        const node = formatRouterItem(item)
        nodeMap.set(node.id, node)
    })

    // 建立父子关系
    const buildTree = (parentId: string | number, currentLevel: number) => {
        const children: TreeNode[] = []
        list.forEach((item) => {
            const node = nodeMap.get(item.id)
            if (!node)
                return

            if (item.parentId == parentId) {
                // 超过4级的菜单设置为隐藏
                // node.hidden = currentLevel > 4

                if (parentId === pid) {
                    result.push({ ...node, component: 'Layout', path: `/${node.path}` || '/' })
                }
                else {
                    const parent = nodeMap.get(parentId)
                    if (parent) {
                        if (!parent?.children) {
                            parent.children = []
                        }
                        if (!node?.component) {
                            node.component = 'ParentView'
                        }
                        parent.children.push(node)
                    }
                }

                // 递归处理子节点
                const childNodes = buildTree(item.id, currentLevel + 1)
                if (childNodes.length > 0) {
                    node.children = childNodes
                }
            }
        })
        return children
    }

    // 从根节点开始构建树
    buildTree(pid, level)

    // 对所有节点的children按sort属性排序
    const sortNodeChildren = (nodes: TreeNode[]) => {
        nodes.forEach((node) => {
            if (node.children && node.children.length > 0) {
                // 对子节点按sort属性排序
                node.children.sort((a, b) => (a.sort || 0) - (b.sort || 0))
                // 递归排序子节点的children
                sortNodeChildren(node.children)
            }
        })
    }

    // 对顶层节点按sort属性排序
    result.sort((a, b) => (a.sort || 0) - (b.sort || 0))
    // 递归排序所有子节点
    sortNodeChildren(result)

    // 移除最后一级的 children 属性
    const removeEmptyChildren = (nodes: TreeNode[]) => {
        nodes.forEach((node) => {
            if (node?.children && node.children.length === 0) {
                delete node.children
                delete node.redirect
                delete node.alwaysShow
            }
            else if (node?.children) {
                node.alwaysShow = true // 设置 alwaysShow 为 true
                // 递归调用以处理子节点
                removeEmptyChildren(node.children)
            }
        })
    }

    removeEmptyChildren(result)

    // console.log("🚀 ~ listToTree ~ result:", result)

    return result
}
